package com.baizhi.controller;

import com.baizhi.entity.Banner;
import com.baizhi.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/banner")
public class BannerController {

    //把字符串转换成日期格式，在修改或者添加的时候，可以将用户输入或者选择的字符串格式的时间转换成日期格式
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值，false:不能为空值

    }

    @Autowired
    private BannerService bannerService;

    //查询所有轮播图  分页查询
    @RequestMapping("/listBanner")
    Map listBanner(int page, int limit){
        return bannerService.listBanner(page,limit);
    }

    //添加轮播图
    @RequestMapping("/insertBanner")
    public Map insertBanner(Banner banner, MultipartFile imageUrl, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/img");
        //重命名，防止同名文件被覆盖
        String newFileName = new Date().getTime() + "_" + imageUrl.getOriginalFilename();
        imageUrl.transferTo(new File(realPath + "/" + newFileName));

        banner.setBannerImageUrl("http://localhost:8989/cmfzdemo/img/"+imageUrl.getOriginalFilename());

        return bannerService.insertBanner(banner);
    }

    //查询轮播图对象
    @RequestMapping("/selectBannerById")
    public Banner selectBannerById(Integer id){
        return bannerService.selectBannerById(id);
    }

    //修改轮播图
    @RequestMapping("/updateBanner")
    public Map updateBanner(Banner banner,MultipartFile imageUrl, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/img");
        //重命名，防止同名文件被覆盖
        String newFileName = new Date().getTime() + "_" + imageUrl.getOriginalFilename();
        imageUrl.transferTo(new File(realPath + "/" + newFileName));

        banner.setBannerImageUrl("http://localhost:8989/cmfzdemo/img/"+imageUrl.getOriginalFilename());

        return bannerService.updateBanner(banner);
    }

    //批量删除轮播图
    @RequestMapping("/multiDelete")
    public Map multiDelete(Integer[] ids){
     //   System.out.println("-----------");
      //  System.out.println(ids);
        return bannerService.multiDelete(ids);
    }
}
